package com.dayi.activity.coachstudy;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Environment;
import android.os.Looper;
import android.text.TextUtils;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.Surface;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListPopupWindow;
import android.widget.Spinner;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.load.resource.gif.GifDrawable;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.dayi.R;
import com.dayi.R2;
import com.dayi.bean.BaseBean;
import com.dayi.bean.DeleteFileReplyBean;
import com.dayi.bean.GradeBean;
import com.dayi.bean.coachstudy.StudyUploadHomework;
import com.lib.app.ARouterPathUtils;
import com.lib.app.CodeUtil;
import com.lib.fastkit.db.shared_prefrences.SharedPreferenceManager;
import com.lib.fastkit.db.shared_prefrences.interfaces.UserCacheInterface;
import com.lib.fastkit.http.ok.HttpUtils;
import com.lib.fastkit.utils.json_deal.lib_mgson.MGson;
import com.lib.fastkit.utils.log.LogUtil;
import com.lib.fastkit.utils.permission.custom.PermissionUtil;
import com.lib.fastkit.utils.share.tool.StringUtil;
import com.lib.fastkit.views.dialog.http.DialogUtils;
import com.lib.fastkit.views.dialog.normal.CoachAIStudyDialog;
import com.lib.fastkit.views.dialog.normal.OneButtonDialog;
import com.lib.http.call_back.HttpNormalCallBack;
import com.lib.ui.activity.BaseAppActivity;
import com.lib.utls.upload.QiNiuUploadTask;
import com.lib.utls.upload.initerface.FileUploadListener;
import com.lib.view.navigationbar.NomalNavigationBar;

import java.io.File;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import androidx.annotation.Nullable;
import butterknife.BindView;
import cn.bingoogolapple.photopicker.activity.BGAPhotoPickerActivity;
import cn.bingoogolapple.photopicker.activity.BGAPhotoPickerPreviewActivity;
import cn.bingoogolapple.photopicker.widget.BGASortableNinePhotoLayout;
import pub.devrel.easypermissions.AfterPermissionGranted;

import static com.taobao.accs.init.Launcher_InitAccs.mContext;

@Route(path = ARouterPathUtils.Tablet_DaYi_CoachUploadAskActivity)
public class CoachUploadAskActivity extends BaseAppActivity implements BGASortableNinePhotoLayout.Delegate {

    @BindView(R2.id.add_photos)
    BGASortableNinePhotoLayout addPhotos;
    @BindView(R2.id.tv_sure)
    TextView tvSure;

    @BindView(R2.id.iv_gift)
    ImageView ivGift;

    private static final int PRC_PHOTO_PICKER = 1;
    private static final int RC_CHOOSE_PHOTO = 1;
    private static final int RC_PHOTO_PREVIEW = 2;

    List<String> imgList = new ArrayList<>();//装载上传成功之后图片地址的容器

    //需要删除图片hash地址的集合
    List<String> deleteItemList = new ArrayList<>();

    //装载年级的实体类和字符串
    //装载科目的实体类和字符串
//    private GradeBean GradeBean;
//    private String chooseGradeStr = "";
//    private String chooseGradeId = "";
    //年级、科目字典装载容器
//    private List<String> mDataCourse = new ArrayList<>();

//    private String[] gradeArr;

    private View parentView;

    DialogUtils dialogUtils;

    @Override
    protected void onCreateView() {

        dialogUtils = new DialogUtils();

        initTitle();

        initView();

        //获取年级列表
        initGradeList();

//        gradeArr = getResources().getStringArray(R.array.array_choose_grade);

        tvSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (imgList.size() == 0) {
                    if (addPhotos.getItemCount() == 0) {
                        showToast("请先上传家庭作业图片哦！");
                    } else {
                        showToast("图片正在上传，请稍等！");
                    }
                } else {

                    parentView = v;
//                    showChooseDialog();

                    CoachAIStudyDialog.getInstance()
                            .setTitle("温馨提示")
                            .setContent("本次辅导将扣除 1 辅导次数，是否确定继续寻找辅导老师？")
                            .setCancelListener(new CoachAIStudyDialog.CancelListener() {
                                @Override
                                public void onCancel() {

                                }
                            })
                            .setSureListener(new CoachAIStudyDialog.SurelListener() {
                                @Override
                                public void onSure() {

                                    //因需要多端登录，为保证推送的准确性，需要先确定推送的设备
                                    bindYouMengToken();
                                    uploadImgToService();
                                }
                            }).show(getSupportFragmentManager());
                }
            }
        });

        initGiftGif();
    }

    private void bindYouMengToken() {

        if (StringUtil.isNotEmpty(SharedPreferenceManager.getInstance(this).getUserCache().getYouMengPushToken(), true)) {
            LogUtil.e("@@@@@@@@@@@@@@@@@@@@@@@" + SharedPreferenceManager.getInstance(this).getUserCache().getYouMengPushToken());
            HttpUtils.with(this)
                    .addParam("requestType", "SET_APPID")
                    .addParam("token", SharedPreferenceManager.getInstance(this).getUserCache().getUserToken())
                    .addParam("app_id", SharedPreferenceManager.getInstance(this).getUserCache().getYouMengPushToken())
                    .addParam("client", "XSTTablet")
                    .execute(new HttpNormalCallBack<BaseBean>() {
                        @Override
                        public void onSuccess(BaseBean result) {

                        }

                        @Override
                        public void onError(String e) {

                        }
                    });
        }
    }

    private void initGiftGif() {

        Glide.with(this).load(R.drawable.work_gift).listener(new RequestListener() {
            @Override
            public boolean onLoadFailed(@Nullable GlideException e, Object model, Target target, boolean isFirstResource) {
                return false;
            }

            @Override
            public boolean onResourceReady(Object resource, Object model, Target target, DataSource dataSource, boolean isFirstResource) {
                if (resource instanceof GifDrawable) {
                    //加载一次
                    ((GifDrawable) resource).setLoopCount(-1);
                }

                return false;
            }

        }).into(ivGift);

    }


    private void uploadImgToService() {

        String imgJson = MGson.newGson().toJson(imgList);
        LogUtil.e("图片json数据为：" + imgJson);
        HttpUtils.with(this)
                .addParam("requestType", "STUDENT_WAITING_INTERFACE")
                .addParam("token", SharedPreferenceManager.getInstance(this).getUserCache().getUserToken())
                .addParam("image_hash", imgJson)
//                .addParam("grade_id", chooseGradeId)
                .execute(new HttpNormalCallBack<StudyUploadHomework>() {
                    @Override
                    public void onSuccess(StudyUploadHomework result) {

                        if (CodeUtil.CODE_200 == result.getCode()) {
                            showToast("作业上传成功，辅导老师正在赶来！");

                            ARouter.getInstance().build(ARouterPathUtils.Tablet_DaYi_CoachWaitAnswerActivity).navigation();

                            //将是否等待数据设置为1，方便外部显示
                            UserCacheInterface userCacheInterface = SharedPreferenceManager.getInstance(CoachUploadAskActivity.this).getUserCache();
                            userCacheInterface.setIsWait(1);

                            finish();
                        } else if (479 == result.getCode() || 480 == result.getCode()) {//次数已不够或您还不是AI作业辅导云用户

                            OneButtonDialog.getInstance()
                                    .setTitle("温馨提示")
                                    .setContent(result.getMsg())
                                    .setSureListener(new OneButtonDialog.SurelListener() {
                                        @Override
                                        public void onSure() {

                                        }
                                    }).show(getSupportFragmentManager());

                        }
                    }

                    @Override
                    public void onError(String e) {

                    }
                });

    }

    private void initView() {
        //初始化图片选择器
        addPhotos.setData(null);
        addPhotos.setMaxItemCount(20);
        addPhotos.isEditable();
        addPhotos.isPlusEnable();

        addPhotos.setDelegate(this);
    }


    protected void initTitle() {
        NomalNavigationBar navigationBar = new
                NomalNavigationBar.Builder(this)
                .setTitle("上传家庭作业")
                .builder();

    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_study_uploadimg;
    }


    public void onClickAddNinePhotoItem(BGASortableNinePhotoLayout sortableNinePhotoLayout, View view, int position, ArrayList<String> models) {
        choicePhotoWrapper();
    }

    public void onClickDeleteNinePhotoItem(BGASortableNinePhotoLayout sortableNinePhotoLayout, View view, int position, String model, ArrayList<String> models) {

        LogUtil.e("mPhotosSnpld的子类个数为：" + addPhotos.getChildCount());
        if (position < addPhotos.getChildCount()) {
            addPhotos.removeItem(position);
        }
        LogUtil.e("删除图片之前imgList的长度为：" + imgList.size());
        if (imgList.size() > 0 && imgList.size() > position) {
            //获取到指定位置的图片id,上传给服务器
            //deletePrepareImg(courseImgList.get(position).getCourseware_id() + "");

            //将删除的图片hash地址保存到容器中，将图片从七牛删除
            String url = "\"" + imgList.get(position) + "\"";
            deleteItemList.add(url);

            sendImageDeleteForQN();

            //从图片集合中删除指定item
            imgList.remove(position);
        }

    }

    public void onClickNinePhotoItem(BGASortableNinePhotoLayout sortableNinePhotoLayout, View view, int position, String model, ArrayList<String> models) {
        Intent photoPickerPreviewIntent = new BGAPhotoPickerPreviewActivity.IntentBuilder(this)
                .previewPhotos(models) // 当前预览的图片路径集合
                .selectedPhotos(models) // 当前已选中的图片路径集合
                .maxChooseCount(addPhotos.getMaxItemCount()) // 图片选择张数的最大值
                .currentPosition(position) // 当前预览图片的索引
                .isFromTakePhoto(false) // 是否是拍完照后跳转过来
                .build();
        startActivityForResult(photoPickerPreviewIntent, RC_PHOTO_PREVIEW);
    }

    @Override
    public void onNinePhotoItemExchanged(BGASortableNinePhotoLayout sortableNinePhotoLayout, int fromPosition, int toPosition, ArrayList<String> models) {

    }


    @AfterPermissionGranted(PRC_PHOTO_PICKER)
    private void choicePhotoWrapper() {

//        Intent photoPickerIntent = new BGAPhotoPickerActivity.IntentBuilder(CoachUploadAskActivity.this)
////                    .maxChooseCount(mPhotosSnpl.getMaxItemCount() - mPhotosSnpl.getItemCount()) // 图片选择张数的最大值
//                .maxChooseCount(1)
//                .selectedPhotos(null) // 当前已选中的图片路径集合
//                .pauseOnScroll(false) // 滚动列表时是否暂停加载图片
//                .build();
//        startActivityForResult(photoPickerIntent, RC_CHOOSE_PHOTO);

        // 拍照后照片的存放目录，改成你自己拍照后要存放照片的目录。如果不传递该参数的话就没有拍照功能
        String savePath = Environment.getExternalStorageDirectory() + "/xstablet/UploadWorkPhoto/";
        File doodleFile = new File(savePath);
        if (!doodleFile.exists()) {
            doodleFile.mkdirs();
        }

        Intent photoPickerIntent = new BGAPhotoPickerActivity.IntentBuilder(CoachUploadAskActivity.this)
                .cameraFileDir(doodleFile) // 拍照后照片的存放目录，改成你自己拍照后要存放照片的目录。如果不传递该参数的话则不开启图库里的拍照功能
                .maxChooseCount(1) // 图片选择张数的最大值
                .selectedPhotos(null) // 当前已选中的图片路径集合
                .pauseOnScroll(false) // 滚动列表时是否暂停加载图片
                .build();

        startActivityForResult(photoPickerIntent, RC_CHOOSE_PHOTO);

//        PermissionUtil.getInstance(CoachUploadAskActivity.this).externalMain(new PermissionUtil.RequestPermission() {
//            @Override
//            public void onRequestPermissionSuccess() {
//
//
//
//            }
//
//            @Override
//            public void onRequestPermissionFailure() {
//
//            }
//        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == RC_CHOOSE_PHOTO) {

            addPhotos.addMoreData(BGAPhotoPickerActivity.getSelectedPhotos(data));

            //选择成功之后上传图片到七牛
            List<String> imgList = BGAPhotoPickerActivity.getSelectedPhotos(data);
            LogUtil.e("图片的本地地址为：" + imgList.get(0));

            upLoadImage(imgList.get(0));

        }
    }

    /**
     * 删除七牛服务器中用户上传成功后删除的图片
     */
    public void sendImageDeleteForQN() {

        if (deleteItemList == null || deleteItemList.size() == 0) {
            return;
        } else {
            LogUtil.e("deleteItemList的长度为：" + deleteItemList.size());
        }

        HttpUtils.with(this)
                .addParam("requestType", "DELETE_QINIU_FILE")
                .addParam("hash_list", deleteItemList)
                .execute(new HttpNormalCallBack<DeleteFileReplyBean>() {
                    @Override
                    public void onSuccess(DeleteFileReplyBean result) {
                        if (CodeUtil.CODE_200 == result.getCode()) {
                            LogUtil.e("图片删除成功");
                        }
                    }

                    @Override
                    public void onError(String e) {

                    }
                });
    }

    /**
     * 上传图片到七牛
     *
     * @param compressPath
     */
    public void upLoadImage(String compressPath) {

        dialogUtils.showNormalDialog(this, "图片正在上传中......");

        String token = SharedPreferenceManager.getInstance(this).getUserCache().getQiNiuToken();
        LogUtil.e("333333333333333333333" + token);

        QiNiuUploadTask qiNiuUploadTask = new QiNiuUploadTask(this);
        qiNiuUploadTask.setFileUploadListener(new FileUploadListener() {
            @Override
            public void onProgress(int progress) {

            }

            @Override
            public void onSuccess(String s) {

                dialogUtils.dismiss();

                if ("".equals(s) || null == s || "null".equals(s) || s.length() < 5) {
                    showToast("上传失败，请重新选择!");

                } else {

                    showToast("图片上传成功");

                    imgList.add(s);
                }
            }

            @Override
            public void onError(String e) {

                dialogUtils.dismiss();
                Looper.prepare();
                showToast("图片上传失败");
                Looper.loop();// 进入loop中的循环，查看消息队列
            }
        });
        qiNiuUploadTask.execute(compressPath, SharedPreferenceManager.getInstance(this).getUserCache().getQiNiuToken());

    }

    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {

    }

    private void showChooseDialog() {
//
//        View view = LayoutInflater.from(this).inflate(R.layout.dialog_newdayi_choosegrade, null);
//
//        ImageView iv_hide = view.findViewById(R.id.new_iv_hide);
//        Spinner spinGrade = view.findViewById(R.id.new_spin_grade);
//        spinGrade.setDropDownVerticalOffset(112);
//
//        try {
//            Field popup = Spinner.class.getDeclaredField("mPopup");
//            popup.setAccessible(true);
//            // Get private mPopup member variable and try cast to ListPopupWindow
//            ListPopupWindow popupWindow = (ListPopupWindow) popup.get(spinGrade);
//            // Set popupWindow height to 500px
//            popupWindow.setHeight(600);
//        } catch (Exception e) {
//            // silently fail...
//            LogUtil.e("Exception为：" + e.getMessage().toString());
//        }
//
//        spinGrade.setAdapter(new TvArrayAdapter(this, gradeArr));
//
//        LinearLayout linPay = view.findViewById(R.id.new_lin_pay);
//        final AlertDialog dialog = new AlertDialog.Builder(this)
//                .setView(view)
//                .setCancelable(true)
//                .show();
//
//        spinGrade.setOnItemSelectedListener(new GradeSpinnerAdapter());
//
//        iv_hide.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                dialog.dismiss();
//            }
//        });
//
//        linPay.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//
//                if (TextUtils.isEmpty(chooseGradeStr)) {
//                    showToast("选择年级之后才能连线老师哦");
//                    return;
//                } else {
//
//                    LogUtil.e("选择的年级是：" + chooseGradeStr);
//
//                    if (GradeBean != null) {
//                        chooseGradeId = getGradeId(GradeBean, chooseGradeStr);
//                    } else {
//
//                        initGradeList();
//                    }
//
//                    if (StringUtil.isNotEmpty(chooseGradeId, true)) {
//                        LogUtil.e("选择的年级的Id是：" + chooseGradeId);
//                        //askChoosePopupUtil.dismiss();
//                        dialog.dismiss();
//
//
//
//                    }
//                }
//            }
//        });
    }

    public class TvArrayAdapter extends android.widget.BaseAdapter {

        private String[] mStringArray;
        private Context context;

        public TvArrayAdapter(Context context, String[] mStringArray) {
            this.context = context;
            this.mStringArray = mStringArray;
        }

        @Override
        public int getCount() {
            return mStringArray.length;
        }

        @Override
        public Object getItem(int position) {
            return mStringArray[position];
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getDropDownView(int position, View convertView, ViewGroup parent) {

            LayoutInflater _LayoutInflater = LayoutInflater.from(context);
            convertView = _LayoutInflater.inflate(R.layout.item_select, null);
            if (convertView != null) {
                TextView tv = (TextView) convertView.findViewById(R.id.tv_text);
                tv.setText(mStringArray[position]);
            }
            return convertView;

        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            LayoutInflater _LayoutInflater = LayoutInflater.from(context);
            convertView = _LayoutInflater.inflate(R.layout.item_select, null);
            if (convertView != null) {
                TextView tv = (TextView) convertView.findViewById(R.id.tv_text);
                tv.setText(mStringArray[position]);
            }
            return convertView;

        }
    }

    class GradeSpinnerAdapter implements AdapterView.OnItemSelectedListener {

        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

            String item = (String) parent.getItemAtPosition(position);
            if (StringUtil.isNotEmpty(item, true)) {
//                chooseGradeStr = item;
            }
            LogUtil.e("选中的年级为：" + item);
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    }

    /**
     * 获取科目字典数据
     */
    private void initGradeList() {
//        mDataCourse.clear();
//        HttpUtils.with(this)
//                .post()
//                .addParam("requestType", "DICT_GRADE_LIST")
//                .execute(new HttpNormalCallBack<GradeBean>() {
//                    @Override
//                    public String onSuccess(GradeBean result) {
//                        if (CodeUtil.CODE_200 == result.getCode()) {
//
//                            if (result.getObj() != null) {
////                                GradeBean = result;
//                                for (int i = 0; i < result.getObj().size(); i++) {
//                                    mDataCourse.add(result.getObj().get(i).getName());
//                                }
//                            }
//                        }
//                        return null;
//                    }
//
//                    @Override
//                    public void onError(String e) {
//
//                    }
//                });

    }

    /**
     * 将String科目字符串转为相对应的科目Id
     *
     * @param gradeBean
     * @param str
     * @return
     */
    private String getGradeId(GradeBean gradeBean, String str) {

        if (gradeBean != null) {
            for (int i = 0; i < gradeBean.getObj().size(); i++) {
                if (str.equals(gradeBean.getObj().get(i).getName())) {
                    return gradeBean.getObj().get(i).getId();
                }
            }
        }
        return null;
    }


//    public int rotationForOrientationLw(int orientation, int lastRotation, boolean displayEnabled) {
//
//        if (mPortraitRotation < 0) {
//// Initialize the rotation angles for each orientation once.
//            Display d = ((WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
//            if (d.getWidth() > d.getHeight()) {
//                mPortraitRotation = Surface.ROTATION_270;//Surface.ROTATION_90;
//                mLandscapeRotation = Surface.ROTATION_0;
//
//            } else {
//                mPortraitRotation = Surface.ROTATION_0;
//                mLandscapeRotation = Surface.ROTATION_270;//Surface.ROTATION_90;
//
//
//            }
//        }
//
//        return mPortraitRotation;
//    }

}